#!/usr/bin/env python3
"""
Prometheus 监控工具函数模块
提供通用的工具函数和辅助方法
"""

import logging
from datetime import datetime
from typing import Dict, Any, List

logger = logging.getLogger(__name__)

class AlertUtils:
    """告警工具类"""
    
    @staticmethod
    def format_timestamp(timestamp: float) -> str:
        """格式化时间戳"""
        if timestamp and timestamp > 0:
            return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
        return '未知'
    
    @staticmethod
    def get_severity_name(severity: str) -> str:
        """获取严重程度名称"""
        severity_map = {
            "info": "信息",
            "warning": "警告",
            "critical": "严重",
            "emergency": "紧急"
        }
        return severity_map.get(severity.lower() if severity else "", f"未知({severity})")
    
    @staticmethod
    def get_severity_emoji(severity: str) -> str:
        """获取严重程度对应的表情符号"""
        emoji_map = {
            "info": "ℹ️",
            "warning": "⚠️",
            "critical": "🔥",
            "emergency": "💥"
        }
        return emoji_map.get(severity.lower() if severity else "", "❓")
    
    @staticmethod
    def is_critical_alert(alert: Dict[str, Any]) -> bool:
        """判断是否为严重告警"""
        severity = alert.get('severity', '').lower()
        return severity in ['critical', 'emergency']
    
    @staticmethod
    def group_alerts_by_service(alerts: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
        """按服务分组告警"""
        grouped = {}
        for alert in alerts:
            instance = alert.get('instance', '未知实例')
            service_name = AlertUtils._extract_service_name(instance)
            if service_name not in grouped:
                grouped[service_name] = []
            grouped[service_name].append(alert)
        return grouped
    
    @staticmethod
    def _extract_service_name(instance: str) -> str:
        """从 Pod 实例名提取服务名"""
        if ':' in instance:
            instance = instance.split(':')[0]
        
        # 处理 Kubernetes Pod 命名模式: service-name-hash-podid
        parts = instance.split('-')
        if len(parts) >= 3:
            service_parts = parts[:-2]
            return '-'.join(service_parts)
        else:
            return instance
    
    @staticmethod
    def group_alerts_by_severity(alerts: List[Dict[str, Any]]) -> Dict[str, List[Dict[str, Any]]]:
        """按严重程度分组告警"""
        grouped = {}
        for alert in alerts:
            severity = alert.get('severity', 'warning').lower()
            if severity not in grouped:
                grouped[severity] = []
            grouped[severity].append(alert)
        return grouped
    
    @staticmethod
    def get_alert_duration(alert: Dict[str, Any]) -> str:
        """计算告警持续时间"""
        # Prometheus 告警通常不提供开始时间，返回默认值
        return '活跃中'

class ReportFormatter:
    """报告格式化工具类"""
    
    @staticmethod
    def format_alert_summary(alerts: List[Dict[str, Any]]) -> str:
        """格式化告警摘要"""
        if not alerts:
            return "📊 **告警统计**: 当前无告警"
        
        total = len(alerts)
        critical_count = len([a for a in alerts if AlertUtils.is_critical_alert(a)])
        services_count = len(set(AlertUtils._extract_service_name(a.get('instance', '')) for a in alerts))
        
        summary = f"📊 **告警统计**: 总计 **{total}** 个告警"
        if critical_count > 0:
            summary += f"，其中 **{critical_count}** 个严重告警"
        summary += f"，影响 **{services_count}** 个服务"
        
        return summary
    
    @staticmethod
    def format_top_alerts(alerts: List[Dict[str, Any]], limit: int = 5) -> str:
        """格式化优先处理的告警"""
        if not alerts:
            return ""
        
        # 按严重程度排序
        severity_order = {'emergency': 4, 'critical': 3, 'warning': 2, 'info': 1}
        sorted_alerts = sorted(alerts, key=lambda x: severity_order.get(x.get('severity', '').lower(), 0), reverse=True)
        
        result = f"\n🔥 **优先处理告警** (Top {min(limit, len(sorted_alerts))}):\n"
        
        for i, alert in enumerate(sorted_alerts[:limit], 1):
            severity = alert.get('severity', 'warning')
            emoji = AlertUtils.get_severity_emoji(severity)
            severity_name = AlertUtils.get_severity_name(severity)
            instance = alert.get('instance', '未知实例')
            service_name = AlertUtils._extract_service_name(instance)
            alert_name = alert.get('alert_name', '未知告警')
            summary = alert.get('summary', alert.get('description', ''))
            
            result += f"{i}. {emoji} **[{severity_name}]** {service_name}: {alert_name}\n"
            if summary:
                result += f"   详情: {summary}\n"
        
        return result
    
    @staticmethod
    def format_service_summary(alerts: List[Dict[str, Any]]) -> str:
        """格式化服务告警摘要"""
        grouped = AlertUtils.group_alerts_by_service(alerts)
        
        if not grouped:
            return ""
        
        result = f"\n🖥️ **服务告警分布**:\n"
        
        # 按告警数量排序
        sorted_services = sorted(grouped.items(), key=lambda x: len(x[1]), reverse=True)
        
        for service, service_alerts in sorted_services[:10]:  # 最多显示10个服务
            critical_count = len([a for a in service_alerts if AlertUtils.is_critical_alert(a)])
            total_count = len(service_alerts)
            
            result += f"- **{service}**: {total_count} 个告警"
            if critical_count > 0:
                result += f" (其中 {critical_count} 个严重)"
            result += "\n"
        
        return result

class LogUtils:
    """日志工具类 - 参考Zabbix格式"""
    
    @staticmethod
    def log_config_validation(ai_engine: str):
        """记录配置验证信息"""
        logger.info(f"配置验证通过，当前AI引擎: {ai_engine}")
    
    @staticmethod
    def log_operation_start(operation: str):
        """记录操作开始"""
        logger.info(f"🚀 开始执行: {operation}")
    
    @staticmethod
    def log_operation_success(operation: str, details: str = ""):
        """记录操作成功"""
        message = f"✅ 完成: {operation}"
        if details:
            message += f" - {details}"
        logger.info(message)
    
    @staticmethod
    def log_operation_error(operation: str, error: str):
        """记录操作错误"""
        logger.error(f"❌ 失败: {operation} - {error}")
    
    @staticmethod
    def log_config_validation(ai_engine: str):
        """记录配置验证信息"""
        logger.info(f"配置验证通过，当前AI引擎: {ai_engine}")
    
    @staticmethod
    def log_prometheus_connection(prometheus_url: str, success: bool = True):
        """记录Prometheus连接信息"""
        if success:
            logger.info(f"成功连接到 Prometheus 服务: {prometheus_url}")
        else:
            logger.error(f"连接Prometheus失败: {prometheus_url}")
    
    @staticmethod
    def log_alert_stats(alerts_count: int, prometheus_url: str = ""):
        """记录告警统计信息"""
        logger.info(f"📊 Prometheus查询完成: {alerts_count} 个活跃告警")
    
    @staticmethod
    def log_ai_analysis_result(ai_engine: str, success: bool):
        """记录AI分析结果"""
        if success:
            logger.info(f"✅ {ai_engine.title()} AI分析任务完成")
        else:
            logger.error(f"❌ {ai_engine.title()} API分析失败")
    
    @staticmethod
    def log_notification_result(success: bool, alerts_count: int = 0):
        """记录通知发送结果"""
        if success:
            logger.info("✅ 完成: 发送告警报告")
        else:
            logger.error("❌ 失败: 发送告警报告 - 推送失败")
    
    @staticmethod
    def log_task_completion(task_name: str):
        """记录任务完成"""
        logger.info(f"🎯 {task_name} - 任务完成")
    
    @staticmethod
    def log_raw_data_sent(ai_engine: str, data_summary: str):
        """记录发送给AI的原始数据"""
        logger.info("\n" + "="*80)
        logger.info(f"📊 发送给{ai_engine}的原始聚合数据:")
        logger.info("\n" + data_summary)
        logger.info("="*80 + "\n")